package com.l2qq.vben.auth;

import cn.dev33.satoken.stp.StpUtil;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.l2qq.common.kit.CommonKit;

import com.l2qq.common.kit.SaTokenKit;
import com.l2qq.common.model.Account;

public class SaTokenInterceptor implements Interceptor {

    @Override
    public void intercept(Invocation inv) {

        Controller c = inv.getController();
        // 增加登录状态检查
        if (!StpUtil.isLogin()) {
            //c.renderJson(Ret.fail("请重新登录").set("code",401));
            //c.getResponse().setStatus(401);
            c.renderJson(Ret.fail("请重新登录"));
            c.redirect("/");
        }
        // 系统关闭检查
        if (CommonKit.isIsCloseSystem() && Db.queryInt("SELECT count(1) FROM dict WHERE k = 'closeSystem' AND v = 'true' ") > 0) {
            c.renderJson(Ret.fail().set("closeSystem", true));
            return;
        }

        // Sa-Token 登录验证
        try {
            StpUtil.checkLogin();
            //StpUtil.hasPermission()
            Account loginAccount = SaTokenKit.getLoginAccount();
            if (loginAccount == null) {
                c.getResponse().setStatus(401);
                c.renderJson(Ret.fail("请重新登录").set("code", 401));
                c.redirect("/");
            }
            inv.invoke();
        } catch (cn.dev33.satoken.exception.NotLoginException e) {
            c.getResponse().setStatus(401);
            c.renderJson(Ret.fail("请重新登录").set("code", 401));
        }
    }
}